package com.wx.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wx.entity.Weather;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Random;

import static com.wx.utils.BaseUrl.WEATHER;

/**
 * @author DKH
 * @version 1.0.0
 * @createTime 2022年08月25日 12:01:00
 */
@Component
public class StringUtil {

    /**
     * 返回当前时间
     */
    public String getNowTime(){
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 计算2天之间差多少天
     */
    public long getBetweenDay(String datetime){
        LocalDate now = LocalDate.now();
        LocalDate startDate = LocalDate.parse(datetime,DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        return startDate.until(now, ChronoUnit.DAYS);

    }

    /**
     * 获取当地天气
     */
    public Weather getTempByCity(String city){
        String s = HttpClient.getInstance().get(WEATHER.replace("CITY", city));

        JSONObject jsonObject = JSONObject.parseObject(s);
        JSONObject data = jsonObject.getJSONObject("data");

        JSONArray forecast = data.getJSONArray("forecast");
        JSONObject obj = forecast.getJSONObject(0);

        return new Weather(){{
            setCity(data.getString("city"));
            setCurrentWeather(data.getString("wendu")+"℃");
            setGanmao(data.getString("ganmao"));
            setDate(obj.getString("date"));
            setHigh(obj.getString("high"));
            setLow(obj.getString("low"));
            setFx(obj.getString("fengxiang"));
            setType(obj.getString("type"));
        }};
    }


    /**
     * 获取上下午
     */
    public String getAmOrPm(){
        Calendar rightNow = Calendar.getInstance();
        int moa = rightNow.get(Calendar.AM_PM);

        return moa == 1 ? "下午好" : "上午好";
    }

    /**
     * 随机生成16进制颜色
     */
    public String getGRB(){
        //红色
        String red;
        //绿色
        String green;
        //蓝色
        String blue;
        //生成随机对象
        Random random = new Random();
        //生成红色颜色代码
        red = Integer.toHexString(random.nextInt(256)).toUpperCase();
        //生成绿色颜色代码
        green = Integer.toHexString(random.nextInt(256)).toUpperCase();
        //生成蓝色颜色代码
        blue = Integer.toHexString(random.nextInt(256)).toUpperCase();

        //判断红色代码的位数
        red = red.length()==1 ? "0" + red : red ;
        //判断绿色代码的位数
        green = green.length()==1 ? "0" + green : green ;
        //判断蓝色代码的位数
        blue = blue.length()==1 ? "0" + blue : blue ;
        //生成十六进制颜色值
        return "#"+red+green+blue;

    }

    public static void main(String[] args) {
        System.out.println(new StringUtil().getTempByCity("沧州"));
    }

}
